home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 2 / Atari Mega Archive CD - Volume 2.iso / minix / up1510b.tgz / up1510b / src / commands / rev.c < prev    next >
C/C++ Source or Header  |  1990-07-19  |  1KB  |  70 lines

  1. /* rev - reverse an ASCII line      Authors: Paul Polderman & Michiel Huisjes */
  2.  
  3. #include <sys/types.h>
  4. #include <fcntl.h>
  5. #include <blocksize.h>
  6.  
  7. #ifndef EOF
  8. #define    EOF    ((char) -1)
  9. #endif
  10.  
  11.  
  12. int fd;                /* File descriptor from file being read */
  13.  
  14. main(argc, argv)
  15. int argc;
  16. char *argv[];
  17. {
  18.   register unsigned short i;
  19.  
  20.   if (argc == 1) {        /* If no arguments given, use stdin as input */
  21.     fd = 0;
  22.     rev();
  23.     exit(0);
  24.   }
  25.   for (i = 1; i < argc; i++) {    /* Reverse each line in arguments */
  26.     if ((fd = open(argv[i], O_RDONLY)) < 0) {
  27.         std_err("Cannot open ");
  28.         std_err(argv[i]);
  29.         std_err("\n");
  30.         continue;
  31.     }
  32.     rev();
  33.     close(fd);
  34.   }
  35.   exit(0);
  36. }
  37.  
  38.  
  39.  
  40.  
  41. rev()
  42. {
  43.   char output[BLOCK_SIZE];    /* Contains a reversed line */
  44.   register unsigned short i;    /* Index in output array */
  45.  
  46.   do {
  47.     i = BLOCK_SIZE - 1;
  48.     while ((output[i] = nextchar()) != '\n' && output[i] != EOF) i--;
  49.     write(1, &output[i + 1], BLOCK_SIZE - 1 - i); /* write reversed line */
  50.     if (output[i] == '\n')    /* and write a '\n' */
  51.         write(1, "\n", 1);
  52.   } while (output[i] != EOF);
  53. }
  54.  
  55.  
  56.  
  57.  
  58. char buf[BLOCK_SIZE];
  59. nextchar()
  60. {                /* Does a sort of buffered I/O */
  61.   static int n = 0;        /* Read count */
  62.   static int i;            /* Index in input buffer to next character */
  63.  
  64.   if (--n <= 0) {        /* We've had this block. Read in next block */
  65.     n = read(fd, buf, BLOCK_SIZE);
  66.     i = 0;            /* Reset index in array */
  67.   }
  68.   return((n <= 0) ? EOF : buf[i++]);    /* Return -1 on EOF */
  69. }
  70.